﻿using IOA.MES.Business;
using IOA.MES.Common;
using IOA.MES.DataAccess.VModel;
using IOA.MES.TcpApi.Models.Request;
using IOA.MES.TcpApi.Models.Response.FootProtectionServer;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http;

namespace IOA.MES.TcpApi.Controllers
{
    /// <summary>
    /// 包护脚机接口
    /// </summary>
    public class FootProtectionServerController : ApiController
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 分拣组件
        /// </summary>
        [HttpPost]
        public ResultJson<PlcHandleResponse> PlcHandle([FromBody] PlcHandleByteRequest request)
        {
            var barCode = "";
            try
            {
                //心跳包
                if (!request.Data.Skip(1).Any(_ => _ != 0x00))
                {
                    return new ResultJson<PlcHandleResponse>(new PlcHandleResponse { Data = new List<byte> { request.Data[0], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } });
                }

                var codeLength = Convert.ToInt32(request.Data[4]);
                barCode = Encoding.ASCII.GetString(request.Data.Skip(6).Take(codeLength).ToArray(), 0, codeLength);

                var sortRecord = new SortMgr().SortComponent(new VSortRecord
                {
                    BarCode = barCode,
                    MachineId = new MachineMgr().GetMachineByIp(request.ClientIpHost)?.PkId ?? 0
                });

                var bytes = new List<byte> { 0x00, 0x00, 0x01, 0x00 };
                if (sortRecord == null)
                {
                    //默认包护脚、不翻转
                    bytes.AddRange(new byte[] { 0x01, 0x00, 0x02, 0x00, 0x00, 0x00 });
                    logger.Info($"组件包护角结果：{barCode}，操作失败");
                }
                else
                {
                    if (sortRecord.FootProtect == true)
                    {
                        bytes.Add(0x01);
                    }
                    else
                    {
                        bytes.Add(0x02);
                    }
                    bytes.Add(0x00);

                    if (sortRecord.OverTurn == true)
                    {
                        bytes.Add(0x01);
                    }
                    else
                    {
                        bytes.Add(0x02);
                    }
                    bytes.Add(0x00);

                    bytes.AddRange(new byte[] { Convert.ToByte(sortRecord.StackNo), 0x00 });
                    logger.Info($"组件包护角结果：{barCode}，" + (bytes[4] == 0x01 ? "包护角，" : "不保护角，") + (bytes[6] == 0x01 ? "翻转" : "不翻转"));
                }

                return new ResultJson<PlcHandleResponse>(new PlcHandleResponse { Data = bytes });
            }
            catch (MultiLanBizException ex)
            {
                var msg = $"包护脚异常，组件条码：{barCode}，异常代码：{ex.ErrCode}，异常信息：{ex.Message}";
                logger.Error(msg);
                return new ResultJson<PlcHandleResponse>(new PlcHandleResponse
                {
                    ErrMsg = msg,
                    Data = new List<byte> { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
                });
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, $"包护脚异常，组件条码：{barCode}，客户端IP：{request.ClientIpHost}，异常信息：{ex.Message}，报文：{Encoding.ASCII.GetString(request.Data.ToArray(), 0, request.Data.Count)}");
                return new ResultJson<PlcHandleResponse>(new PlcHandleResponse
                {
                    ErrMsg = "系统错误",
                    Data = new List<byte> { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
                });
            }
        }
    }
}
